package ie.dkit.semanticPhotoWeb.client.panels.photo;

import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;

public class UploadPhotoWindow extends Window {

	private FileUpload upload;

	/**
	 * Creates a new Upload window and show it from the animation target
	 * @param animationTargetID the animationTargetID
	 * @param username the username
	 * @param albumname the albumname
	 */
	public UploadPhotoWindow(String animationTargetID, String username,
			String albumname) {
		super("Please select photo", true, false);
		// Fix due issues..
		setSize(250, 80);
		// Create a FormPanel and point it at a service.
		final FormPanel form = new FormPanel();
		form.setAction("http://picasaweb.google.com/data/feed/api/user/"
				+ username + "/album/" + albumname);

		// Because we're going to add a FileUpload widget, we'll need to set the
		// form to use the POST method, and multipart MIME encoding.
		// form.setEncoding(FormPanel.ENCODING_MULTIPART);
		form.setMethod(FormPanel.METHOD_POST);
		form.setEncoding(FormPanel.ENCODING_MULTIPART);

		// Create a panel to hold all of the form widgets.
		VerticalPanel panel = new VerticalPanel();
		form.setWidget(panel);

		// Create a FileUpload widget.
		upload = new FileUpload();
		upload.setName("photo");
		panel.add(upload);

		// Add a 'submit' button.
		panel.add(new Button("Submit", new ButtonListenerAdapter() {
			public void onClick(Button button, EventObject e) {
				form.submit();
			}
		}));

		// Add an event handler to the form.
		form.addFormHandler(new FormHandler() {
			public void onSubmit(FormSubmitEvent event) {
				if (!upload.getFilename().endsWith(".jpg")
						&& !upload.getFilename().endsWith(".jpeg")) {
					MessageBox.alert("only jpg and jpeg files are allowed");
					event.setCancelled(true);
				}
			}

			public void onSubmitComplete(FormSubmitCompleteEvent event) {
				MessageBox.alert("Photo submitted");
			}
		});
		add(form);
		this.show(animationTargetID);
	}
}
